//
//  RENetworkTool.m
//  ReelEp
//
//  Created by 孙强 on 2024/7/8.
//  Copyright © 2024 RE. All rights reserved.
//

#import "RENetworkTool.h"

@implementation RENetworkTool


+ (void)POSTString:(NSString *)urlStr andParam:(id)param andBlock:(successBlock)success andError:(errorBlock)failure{
    param = (NSMutableDictionary *)param;
    
    if ([urlStr hasPrefix:@"http://"]||[urlStr hasPrefix:@"https://"]) {
        
    }else {
        urlStr = [BASE_URL stringByAppendingString:urlStr];
    }
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [session.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    session.requestSerializer.timeoutInterval = 15.0f;
    [session.requestSerializer didChangeValueForKey:@"timeoutInterval"];    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    
    if(!param){
        param = [NSMutableDictionary dictionary];
    }
    [self setValueParam:param and:session];
    


    
    [session POST:urlStr parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self markData:responseObject andBlock:success andError:failure andBool:YES];

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [BaseToastView showToast:REAPPString(@"error")];
        
        failure(error);
    }];
    
}

+ (void)POSTImageString:(NSString *)urlStr andParam:(id)param andImage:(UIImage *)image  andBlock:(successBlock)success andError:(errorBlock)failure{

    if ([urlStr hasPrefix:@"http://"]||[urlStr hasPrefix:@"https://"]) {
        
    }else {
        urlStr = [BASE_URL stringByAppendingString:urlStr];
    }

    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];

    [session.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
//    session.requestSerializer = [AFJSONRequestSerializer serializer];

    [session.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    session.requestSerializer.timeoutInterval = 60.0f;
    [session.requestSerializer didChangeValueForKey:@"timeoutInterval"];    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    //添加请求头
    NSString *token = [NSString stringWithFormat:@"%@",GetToken];
    [session.requestSerializer setValue:token forHTTPHeaderField:@"token"];
    [session.requestSerializer setValue:@"app" forHTTPHeaderField:@"app"];

    [session POST:urlStr parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *data;
        //判断图片是不是png格式的文件
        if (UIImagePNGRepresentation(image)) {
            //返回为png图像。
            data = UIImagePNGRepresentation(image);
        }else {
            //返回为JPEG图像。
            data = UIImageJPEGRepresentation(image, 1.0);
        }
//        NSString *fileName = [NSString stringWithFormat:@"%@/%@.png",@"iOS",[self getCurrentTimes]];
        NSString *fileName = [NSString stringWithFormat:@"iOS%@.png",[self getCurrentTimes]];
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"multipart/form-data"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self markData:responseObject andBlock:success andError:failure andBool:YES];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [BaseToastView showToast:REAPPString(@"error")];
        
        failure(error);
    }];
    


}



+ (void)GETString:(NSString *)urlStr andParam:(id)param andBlock:(successBlock)success andError:(errorBlock)failure{
    
    param = (NSMutableDictionary *)param;
    
    if ([urlStr hasPrefix:@"http://"]||[urlStr hasPrefix:@"https://"]) {
        
    }else {
        urlStr = [BASE_URL stringByAppendingString:urlStr];
    }
    
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [session.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    session.requestSerializer.timeoutInterval = 15.0f;
    [session.requestSerializer didChangeValueForKey:@"timeoutInterval"];    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    
    //添加请求头
    if(!param){
        param = [NSMutableDictionary dictionary];
    }
    [self setValueParam:param and:session];


    [session GET:urlStr parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
    
        
        [self markData:responseObject andBlock:success andError:failure andBool:YES];

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [BaseToastView showToast:REAPPString(@"error")];
        
        failure(error);
    }];
    
}


+ (void)POSTNOToastString:(NSString *)urlStr andParam:(id)param andBlock:(successBlock)success andError:(errorBlock)failure{
    param = (NSMutableDictionary *)param;
    
    if ([urlStr hasPrefix:@"http://"]||[urlStr hasPrefix:@"https://"]) {
        
    }else {
        urlStr = [BASE_URL stringByAppendingString:urlStr];
    }
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [session.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    session.requestSerializer.timeoutInterval = 15.0f;
    [session.requestSerializer didChangeValueForKey:@"timeoutInterval"];    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    //添加请求头
    if(!param){
        param = [NSMutableDictionary dictionary];
    }
    [self setValueParam:param and:session];

    
    [session POST:urlStr parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure(error);
    }];
    
}

+ (void)toLogin{
//    if (![GETCURRENTCONTROLLER isKindOfClass:[RELoginViewController class]]) {
//        SetToken(@"");
//        SetLogInState(NO);
//        [BaseToastView showToast:REAPPString(@"登录过期,请重新登录")];
//        RELoginViewController *vc = [RELoginViewController new];
//        vc.hidesBottomBarWhenPushed = YES;
//        [GETCURRENTCONTROLLER.navigationController pushViewController:vc animated:YES];
//        
//    }
    
}

+ (void)POSTJSONString:(NSString *)urlStr andParam:(id)param andBlock:(successBlock)success andError:(errorBlock)failure{
    param = (NSMutableDictionary *)param;
    
    if ([urlStr hasPrefix:@"http://"]||[urlStr hasPrefix:@"https://"]) {
        
    }else {
        urlStr = [BASE_URL stringByAppendingString:urlStr];
    }
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    session.requestSerializer = [AFJSONRequestSerializer serializer];
    
    [session.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    session.requestSerializer.timeoutInterval = 15.0f;
    [session.requestSerializer didChangeValueForKey:@"timeoutInterval"];    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    //添加请求头
    if(!param){
        param = [NSMutableDictionary dictionary];
    }
    [self setValueParam:param and:session];

    
    [session POST:urlStr parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self markData:responseObject andBlock:success andError:failure andBool:YES];

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [BaseToastView showToast:REAPPString(@"error")];
        
        failure(error);
    }];
    
}

//三个必传字段
+ (void)setValueParam:(NSMutableDictionary *)param and:(AFHTTPSessionManager *)session{
        
    //添加请求头
    NSString *token = [NSString stringWithFormat:@"%@",GetToken];
    if(token.length > 0){
        [session.requestSerializer setValue:token forHTTPHeaderField:@"Yizhou-J-Token"];
    }

    //    header["deviceId"] = UIDevice.current.idfa

    
    [session.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"platform"];
    [session.requestSerializer setValue:@"667" forHTTPHeaderField:@"App-Key"];
    
//    header["deviceId"] = UIDevice.current.idfa
    [session.requestSerializer setValue:@"1" forHTTPHeaderField:@"Version-Code"];
    [session.requestSerializer setValue:[YLAppUtils getAppVersion] ? : @"1.0" forHTTPHeaderField:@"Version-Name"];
    [session.requestSerializer setValue:@"plotshort" forHTTPHeaderField:@"Yanhong-Channel"];
    NSString *getIDFA = [YLAppUtils getIDFA] ? : @"";
    [session.requestSerializer setValue:[YLAppUtils getUUID] ? : @"" forHTTPHeaderField:@"deviceId"];
//    [session.requestSerializer setValue:@"cd30c9fb-af99-441e-bb55-91f0b1a9c30d" forHTTPHeaderField:@"deviceId"];

//    [session.requestSerializer setValue:@"User-language" forHTTPHeaderField:@"667"];
//        [session.requestSerializer setValue:@"User-country" forHTTPHeaderField:@""];
        [session.requestSerializer setValue:[self getTimes] forHTTPHeaderField:@"carrier-name"];
    
    NSString *lang = @"en";
    if([GetLang intValue] == 2){
        lang = @"es";
    }
    [session.requestSerializer setValue:lang forHTTPHeaderField:@"User-language-area"];
    
    NSLog(@"param ==== %@",param);

    
}


+ (void)markData:(id)responseObject andBlock:(successBlock)success andError:(errorBlock)failure andBool:(BOOL)isToast{
    REBaseNetworkModel *baseModel = [REBaseNetworkModel yy_modelWithJSON:responseObject];
    
    NSLog(@"responseObject ==== %@",responseObject);
    
    NSString *code = baseModel.code ? : @"";
    BOOL isSuccess = (BOOL)baseModel.success;
//    
//            if (code == 302) {
//                failure(nil);
//                [self toLogin];
//    
//                return ;
//    
//            }
//    
    if ([code isEqualToString:@"000000"] ) {
        
        success(responseObject);
    }
//    else if ([code isEqualToString:@"100019"] ) {
//        
//        success(responseObject);
//    }
    else {
        failure(nil);
        if(isToast){
            NSString *message = [YGUility gjString:baseModel.message];
            if (message.length>0) {
                [BaseToastView showToast:message];
            }else{
                [BaseToastView showToast:REAPPString(@"error")];
            }
        }
    }
    
}

+(NSString*)getCurrentTimes{
    
    int n = (arc4random() % 10000);
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    NSString *timeStamp = [NSString stringWithFormat:@"%.f",time];
    
    NSString *currentTimeString = [NSString stringWithFormat:@"%@%d",timeStamp,n];
    return currentTimeString;
    
}

+(NSString*)getTimes{
    
//    int n = (arc4random() % 10000);
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    NSString *timeStamp = [NSString stringWithFormat:@"%.f",time];
    
    NSString *currentTimeString = [NSString stringWithFormat:@"%@",timeStamp];
    return currentTimeString;
    
}


//+(NSString*)getTimes{
//    
//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    [formatter setDateFormat:@"yyyy/MM/dd/HH/mm/ss"];
//    NSDate *datenow = [NSDate date];
//    NSString *currentTimeString = [formatter stringFromDate:datenow];
//    
//    
////    int n = (arc4random() % 10000);
////    currentTimeString = [NSString stringWithFormat:@"%@%d",currentTimeString,n];
////    
////    NSString *time = [MCUility tenCharactersTimeStamp];
////    currentTimeString = [NSString stringWithFormat:@"%@%d",time,n];
//
//    
//    return currentTimeString;
//    
//}


@end
